package hr.mlab.app.expenses.activities.type;

import hr.mlab.app.expenses.DatabaseOpenHelper;
import hr.mlab.app.expenses.R;
import hr.mlab.app.expenses.widgets.mLabSpinner;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.SimpleCursorAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;

public class TypeDetail extends Activity {
    private TextView tvTypeId;
    private TextView tvTypeName;
    private CheckBox cbIsIncome;
    private Byte     option;
    private Integer  categoryId;
    private Integer  groupId;
    private Integer  typeId;
    private mLabSpinner categorySpinner;
    private Cursor categoryCursor;
    private SpinnerAdapter categoryAdapter;
    private mLabSpinner groupSpinner;
    private Cursor groupCursor;
    private SpinnerAdapter groupAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.typedetail);
   
    	// get input parameters
    	option     = getIntent().getByteExtra("option", (byte) 0);
    	categoryId = getIntent().getIntExtra("categoryId", 0);
    	groupId    = getIntent().getIntExtra("groupId", 0);
    	typeId     = getIntent().getIntExtra("typeId", 0);
   
    	categorySpinner = (mLabSpinner) findViewById(R.id.spnCategory);
    	groupSpinner = (mLabSpinner) findViewById(R.id.spnGroup);
    	
    	categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View itemSelected, 
            						   int selectedItemPosition, long selected) {
            	fillGroupSpinner();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            	fillGroupSpinner();
            }

    	}); 
    	
    	fillCategorySpinner();
    	fillGroupSpinner();

    	initWidgets();
    }
    
    /**
     * Screen initializing
     */
    public void initWidgets() {
        Button btnSave   = (Button) findViewById(R.id.btnSave);
        Button btnCancel = (Button) findViewById(R.id.btnCancel);
        Button btnOk     = (Button) findViewById(R.id.btnOk);
        
		tvTypeId    = (TextView) findViewById(R.id.typeId);
		tvTypeName  = (TextView) findViewById(R.id.typeName);
		cbIsIncome	= (CheckBox) findViewById(R.id.isIncome);
		
		TextView screenTitle = (TextView)findViewById(R.id.screenTitle);
		switch(option) {
		case 1:
			btnOk.setVisibility(View.GONE);
			screenTitle.setText(this.getString(R.string.type)+"-"+this.getString(R.string.btnNew));
			tvTypeId.setText(this.getString(R.string.willBeGenerated));
			tvTypeName.setText("");    		
			break;
		case 2:
			btnOk.setVisibility(View.GONE);
			screenTitle.setText(this.getString(R.string.type)+"-"+this.getString(R.string.btnUpdate));
			initData();
			break;
		case 3:
			btnSave.setVisibility(View.GONE);
			btnCancel.setVisibility(View.GONE);
			screenTitle.setText(this.getString(R.string.type)+"-"+this.getString(R.string.btnDetail));
			initData();
			break;
		case 4:
			btnOk.setVisibility(View.GONE);
			screenTitle.setText(this.getString(R.string.type)+"-"+this.getString(R.string.btnDelete));
			initData();
			break;
		default:
			screenTitle.setText(this.getString(R.string.type));
			Toast.makeText(this, this.getString(R.string.error_invalidOption), Toast.LENGTH_LONG).show();
			returnToCaller(false, null);
			break;
		}
    }
    
    /**
     * Reading data from database
     */
    public void initData() {
		SQLiteDatabase db = (new DatabaseOpenHelper(this)).getReadableDatabase();
		Cursor cursor = db.rawQuery("SELECT _id, typeName FROM " + DatabaseOpenHelper.dbTypes +
		                    		" WHERE  _id = ?", new String[]{typeId.toString()});

		if (cursor.getCount() == 1)
		{
			cursor.moveToFirst();

			tvTypeId.setText(cursor.getString(cursor.getColumnIndex("_id")));
			if(option > 2) {
				tvTypeName.setText(cursor.getString(cursor.getColumnIndex("typeName")), BufferType.NORMAL);
				tvTypeName.setFocusable(false);	
				cbIsIncome.setFocusable(false);
				cbIsIncome.setClickable(false);
				categorySpinner.setFocusable(false);
				categorySpinner.setClickable(false);
				groupSpinner.setFocusable(false);
				groupSpinner.setClickable(false);
			}
			else {
				tvTypeName.setText(cursor.getString(cursor.getColumnIndex("typeName")));
			}
		}
		else {
			Toast.makeText(this, this.getString(R.string.error_noData), Toast.LENGTH_LONG).show();
			returnToCaller(false, null);
		}
		
		categorySpinner.setSelectionById(categoryId);
		groupSpinner.setSelectionById(groupId);
		
		cursor.close();
		db.close();
    }
    
    /**
     * Filling category spinner
     * 
     */
    public void fillCategorySpinner() {
    	SQLiteDatabase db = (new DatabaseOpenHelper(this)).getReadableDatabase();
    	
    	categoryCursor = db.query(DatabaseOpenHelper.dbCategories, 
    						   new String[]{"_id", "categoryName"}, 
    						   null, null, null, null, null);

    	startManagingCursor(categoryCursor);
	
		categoryAdapter = new SimpleCursorAdapter(
						  this, 
						  android.R.layout.simple_spinner_item, 
						  categoryCursor, 
						  new String[] { "categoryName" },
						  new int[] { android.R.id.text1 });
		
		categorySpinner.setAdapter(categoryAdapter);
    }

    /**
     * Filling group spinner
     * 
     */
    public void fillGroupSpinner() {
    	SQLiteDatabase db = (new DatabaseOpenHelper(this)).getReadableDatabase();
    	Integer categoryId = (int) categorySpinner.getSelectedItemId();
    	
     	groupCursor = db.rawQuery("SELECT _id, groupName FROM " + DatabaseOpenHelper.dbGroups + " as g" +
				 				  " left outer join " +  DatabaseOpenHelper.dbGroupCategories + " as gc" +
				 				  " on g._id = gc.groupId WHERE gc.categoryId = ?", 
				 				  new String[]{categoryId.toString()});

    	startManagingCursor(groupCursor);
	
		groupAdapter = new SimpleCursorAdapter(
						  this, 
						  android.R.layout.simple_spinner_item, 
						  groupCursor, 
						  new String[] { "groupName" },
						  new int[] { android.R.id.text1 });
		
		groupSpinner.setAdapter(groupAdapter);
    }

    /**
     * Button save clicked
     * @param view
     */
    public void saveClick(View view) {
        switch(option) {
        case 1:
        	dbInsert();
        	break;
        case 2:
        	dbUpdate();
        	break;
        case 4:
        	dbDelete();
        	break;
        }
        returnToCaller(false, null);
    }
    
    /**
     * Button cancel clicked
     * @param view
     */
    public void cancelClick(View view) {
    	returnToCaller(false, null);
    }
    
    /**
     * Button ok clicked
     * @param view
     */
    public void okClick(View view) {
    	returnToCaller(false, null);
    }
    
    /**
     * Closing this window
     * @param refreshNeeded
     * @param id
     */
    private void returnToCaller(Boolean refreshNeeded, Integer id) {
        Intent intent = new Intent();
        if(refreshNeeded) {
        	intent.putExtra("categoryId", id);
        }
        setResult(Activity.RESULT_OK, intent);
        finish();
    }
    
    /**
     * Insert new type
     */
    private void dbInsert() {
    	Integer id=null;
    	Boolean refreshNeeded = false;
		SQLiteDatabase db = (new DatabaseOpenHelper(this)).getWritableDatabase();
		
		try {
			ContentValues values = new ContentValues();
			values.put("typename", tvTypeName.getText().toString().trim());
			values.put("groupId", (int) groupSpinner.getSelectedItemId());

			id = (int) db.insert(DatabaseOpenHelper.dbTypes, null, values);

			if(id < 1)
				throw new Exception();
			
			refreshNeeded = true;
		} 
		catch(Exception e) {
			id = null;
			Toast.makeText(this, this.getString(R.string.error_insert), Toast.LENGTH_LONG).show();
		}
		finally {
			db.close();
			returnToCaller(refreshNeeded, id);
		}
    }
    
    /**
     * Update type
     */
    private void dbUpdate() {
    	Integer response=null;
		SQLiteDatabase db = (new DatabaseOpenHelper(this)).getWritableDatabase();
		
		try {
			ContentValues values = new ContentValues();
			values.put("typename", tvTypeName.getText().toString().trim());
			values.put("isIncome", cbIsIncome.isChecked() ? 1 : 0);

			response = db.update(DatabaseOpenHelper.dbTypes, values, "_id=?", 
					  					 new String[]{tvTypeId.getText().toString().trim()});
			if(response < 1)
				throw new Exception();
		}			
		catch(Exception e) {
			Toast.makeText(this, this.getString(R.string.error_update), Toast.LENGTH_LONG).show();
		} 
		finally {
			db.close();
			returnToCaller(true, Integer.parseInt(tvTypeId.getText().toString()));
		}
    }
    
    /**
     * Delete type 
     */
    private void dbDelete() {
    	Integer response = null;
		SQLiteDatabase db = (new DatabaseOpenHelper(this)).getWritableDatabase();
	
		try {
			db.delete(DatabaseOpenHelper.dbTypes, "_id=?", new String[]{tvTypeId.getText().toString().trim()});
			response = 0;
		}
		catch(Exception e) {
			Toast.makeText(this, this.getString(R.string.error_delete), Toast.LENGTH_LONG).show();
		} 
		finally {
			db.close();
			returnToCaller(response != null, response);
		}
    }
}


